<template>
    <div class="logic-flow" v-loading="loading">
        <div ref="containerRef" id="container" class="viewport"></div>
        <TeleportContainer :flow-id="flowId"/>
        <UserEditNode ref="userEditNodeRef" :isRead="true" @closeNode="(id:string) => closeNodeCallback(id)"/> 
    </div>
</template>
  
<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue'
import flowApi from '@/api/flow'
import LogicFlow from '@logicflow/core'
import '@logicflow/core/es/index.css'
import "@logicflow/extension/lib/style/index.css"

import { getTeleport } from '@logicflow/vue-node-registry'
import UserEditNode from '../demo/FlowConfig/index.vue' // 引入 UserEditNode 组件

//引入自定义类
import setRegister from './register'
import setEventsListener from './eventsListener'

const loading = ref(false)
const userEditNodeRef = ref();

const flowId = ref('');
const flowDefBusinessData = ref();
provide('flowDefBusinessData',flowDefBusinessData)

// flowResource用于获取edge描述的associatedId
const flowResource = ref()
provide('flowResource',flowResource);

const flowDefId = inject('flowDefId',ref<number>(-1));

const containerRef = ref<HTMLDivElement | null>(null)
const TeleportContainer = getTeleport()
let lf: any;
const flowDefData = ref<any>()
const getFlowData =async () => {    
    loading.value = true;
    // 初始化重新渲染
    lf.render({});
    if( flowDefId.value>0){        
        flowDefData.value = await flowApi.getSpeDetail(flowDefId.value);
        if(flowDefData && flowDefData.value.resource && flowDefData.value.resource.nodes.length>0){                
            lf.render(flowDefData.value.resource);
            lf.translateCenter();
            const yValues = flowDefData.value.resource.nodes.map((node: any) => node.y);
            const minY = Math.min.apply(0, yValues);
            const transform = lf.getTransform();
            const offsetY = - transform.TRANSLATE_Y - minY + 50;
            // console.log('speFlowData',speFlowData.resource.nodes,minY,transform,offsetY)
            lf.translate(0, offsetY);  
        } 
        if(flowDefData && flowDefData.value.business){
            flowDefBusinessData.value = flowDefData.value.business;
        }   
        // 获取接口Resource
        if(flowDefData && flowDefData.value.resource){
            flowResource.value = flowDefData.value.resource; 
        }         
    }
    loading.value = false;
}
let stopWatch: any
onMounted(async () => {
    // 使用nextTick确保DOM完全渲染后再初始化LogicFlow
    await nextTick();
    if (containerRef.value) {
        lf = new LogicFlow({
            container: containerRef.value,
            nodeTextEdit: false,
            edgeTextEdit: false,
            isSilentMode: true,
            background: {
                backgroundColor: 'var(--el-bg-color-overlay)'
            },            
        })
        lf.setTheme({
            snapline: {
                strokeDasharray: "3,3",
                // stroke: 'var(--el-color-primary-light-3)', // 对齐线颜色
                strokeWidth: 1, // 对齐线宽度
            },            
        })      
        
        // 注册事件
        setRegister(lf);
        await getFlowData();     
        // 监听 flowDefId 的变化
        stopWatch = watch(flowDefId,async (_newVal, _oldVal) => {
            // console.log(`flowDefId changed from ${_oldVal} to ${_newVal}`);
            await getFlowData();          
        });
        // 监听事件
        setEventsListener(lf,{userEditNodeRef:userEditNodeRef})  
    }
})
onUnmounted(() => {
    if (stopWatch) {
        stopWatch(); // 调用取消观察的函数
    }    
});
const closeNodeCallback = (_id: string) => {
    // console.log('关1:',_id)
    const graphElement = containerRef.value?.querySelector('div')    
    if (graphElement) {
       graphElement.focus();      
    }
}
</script>
<style scoped lang="scss">
.logic-flow{
    height: 100%;
    width: 100%;
    position: relative;
}
:deep(g.cust-text-node-content){
    g.lf-anchor{
        display: none;
    }
}
#container {
    width: 100%;
    height: 100%
}
</style>
